<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>vue 封装utils.js</title>
</head>

<body>
    <!-- 使用方法 -->
    <!--当是isDebounce时表示是防抖函数，!isDebounce是节流函数，time是执行时间间隔-->
    <Debounce :time='1000' isDebounce>
        <button @click='btn'>btn</button>
    </Debounce>


    <script>
        const debounce = (func, time, isDebounce, ctx) => {
            var timer, lastCall, rtn;
            //防抖函数
            if (isDebounce) {
                rtn = (...params) => {
                    if (timer) clearTimeout(timer);
                    timer = setTimeout(() => {
                        func.apply(ctx, params);
                    }, time);
                };
            } else {//节流函数
                rtn = (...params) => {
                    const now = new Date().getTime();
                    if (now - lastCall < time && lastCall) return;
                    lastCall = now;
                    func.apply(ctx, params);
                };
            }
            return rtn;
        };

        export default {
            name: 'Debounce',
            abstract: true,
            props: {
                time: {
                    type: Number,
                    default: 800,
                },
                events: {
                    type: String,
                    default: 'click',
                },
                isDebounce: {
                    type: Boolean,
                    default: false,
                },
            },
            created() {
                this.eventKeys = this.events.split(',');
                this.originMap = {};
                this.debouncedMap = {};
            },
            render() {
                const vnode = this.$slots.default[0];
                this.eventKeys.forEach(key => {
                    const target = vnode.data.on[key];
                    if (target === this.originMap[key] && this.debouncedMap[key]) {
                        vnode.data.on[key] = this.debouncedMap[key];
                    } else if (target) {
                        this.originMap[key] = target;
                        this.debouncedMap[key] = debounce(
                            target,
                            this.time,
                            this.isDebounce,
                            vnode
                        );
                        vnode.data.on[key] = this.debouncedMap[key];
                    }
                });
                return vnode;
            },
        };
        // 然后我们在main.js入口文件里面全局注册一下

        // import Debounce from '@/config/debounce'

        // Vue.component('Debounce',Debounce)

    </script>
</body>

</html>